package com.peng.leetcode.tree;

/**
 * IsBalanced
 *
 * 剑指 Offer 55 - II. 平衡二叉树
 *
 * @author: lupeng6
 * @create: 2021/2/5 18:11
 */
public class IsBalanced {

    public static void main(String[] args) {

    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int left = dfsTreeHeight(root.left);
        int right = dfsTreeHeight(root.right);
        if (Math.abs(left - right) > 1) {
            return false;
        }
        if (!isBalanced(root.left)) {
            return false;
        }
        if (!isBalanced(root.right)) {
            return false;
        }
        return true;
    }

    int dfsTreeHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = dfsTreeHeight(node.left);
        int right = dfsTreeHeight(node.right);
        int h = Math.max(left, right) + 1;
        return h;
    }
}
